package com.tencent.liteav.trtccalling.zhiyu;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.lifecycle.ViewModelProviders;
import com.tencent.liteav.trtccalling.R;
import com.tencent.liteav.trtccalling.TUICalling;
import com.tencent.liteav.trtccalling.databinding.ActivityChatCallBinding;
import com.tencent.liteav.trtccalling.model.util.TUICallingConstants;
import com.tencent.liteav.trtccalling.ui.audiocall.TUICallAudioView;
import com.tencent.liteav.trtccalling.ui.base.BaseTUICallView;
import com.tencent.liteav.trtccalling.ui.base.Status;
import com.tencent.liteav.trtccalling.ui.base.VideoLayoutFactory;
import com.tencent.liteav.trtccalling.ui.common.Utils;
import com.tencent.liteav.trtccalling.ui.videocall.TUICallVideoView;
import com.tencent.liteav.trtccalling.zhiyu.callback.BooleanCallback;
import com.tencent.liteav.trtccalling.zhiyu.callback.IAnswerCallback;
import com.tencent.liteav.trtccalling.zhiyu.enums.CallFreeTypeEnum;
import com.tencent.liteav.trtccalling.zhiyu.util.YBusUtil;
import com.tencent.liteav.trtccalling.zhiyu.vm.CallVM;
import com.ysg.base.BaseActivity;
import com.ysg.enums.NoDiamondEnum;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YUserUtil;

public class CallActivity extends BaseActivity<ActivityChatCallBinding, CallVM> implements IAnswerCallback {
    private static final String TAG = "BaseCallActivity";
    private BaseTUICallView mCallView;
    private TUICalling.Type mType;
    private TUICalling.Role mRole;
    private String[]        mUserIds;//如果主动拨打，取这个值；对方的txUserId
    private String          mSponsorID;//如果被动接听，取这个值；对方的txUserId
    private VideoLayoutFactory mVideoFactory;
    public static String freeType;//扣费类型：2.音频通话；3.视频通话；4.语音速配；5.视频速配

    //创建C2C语音通话视图
    private BaseTUICallView createAudioView(TUICalling.Role role, TUICalling.Type type, String[] userIds,
                                            String sponsorID, String groupID, boolean isFromGroup) {
        return new TUICallAudioView(this, role, type, userIds, sponsorID, groupID, isFromGroup) {
            @Override
            public void finish() {
                super.finish();
                CallActivity.this.finish();
            }
        };
    }

    //创建C2C视频通话视图
    private BaseTUICallView createVideoView(TUICalling.Role role, TUICalling.Type type, String[] userIds,
                                            String sponsorID, String groupID, boolean isFromGroup) {
        return new TUICallVideoView(this, role, type, userIds, sponsorID, groupID, isFromGroup, mVideoFactory) {
            @Override
            public void finish() {
                super.finish();
                CallActivity.this.finish();
            }
        };
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_chat_call;
    }

    @Override
    public int initVariableId() {
        return 0;
    }

    @Override
    public CallVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(CallVM.class);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        hangup();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CallActivity.freeType = "";//退出恢复默认值
        if (mTimeHandler != null) {
            mTimeHandler.removeCallbacks(mTimeRunnable);
            mTimeRunnable = null;
        }
        Status.mBeginTime = 0;//TODO 通话时间重新开始
    }

    @Override
    public void initParam() {
        super.initParam();
        Intent intent = getIntent();
        if (intent != null){
            mType = (TUICalling.Type) intent.getExtras().get(TUICallingConstants.PARAM_NAME_TYPE);
            mRole = (TUICalling.Role) intent.getExtras().get(TUICallingConstants.PARAM_NAME_ROLE);
            mUserIds = intent.getExtras().getStringArray(TUICallingConstants.PARAM_NAME_USERIDS);
            mSponsorID = intent.getExtras().getString(TUICallingConstants.PARAM_NAME_SPONSORID);

            //获取腾讯id(自己和对方)
            viewModel.txUserIdSelf = YSPUtils.getInstance().getTxCode();
            if (YStringUtil.isNotEmpty(mSponsorID) && mRole == TUICalling.Role.CALLED){
                viewModel.txUserIdOther = mSponsorID;
            } else if (YCollectionUtil.isNotEmpty(mUserIds) && mRole == TUICalling.Role.CALL) {
                viewModel.txUserIdOther = mUserIds[0];
            }
            //性别
            viewModel.sex = YSPUtils.getInstance().getUserSex();
            //设置扣费类型
            if (YStringUtil.isNotEmpty(CallActivity.freeType)){
                //说明从语音匹配或视频匹配进来的
                //TODO 通知匹配界面关闭
                YBusUtil.callMatch();
            }else{
                if (TUICalling.Type.AUDIO == mType){
                    CallActivity.freeType = CallFreeTypeEnum.AUDIO.getType();
                }else{
                    CallActivity.freeType = CallFreeTypeEnum.VIDEO.getType();
                }
            }
        }
    }

    @Override
    public void initView() {
        super.initView();
        Utils.setScreenLockParams(getWindow());
        if (TUICalling.Type.AUDIO == mType) {
            mCallView = createAudioView(mRole, mType, mUserIds, mSponsorID, "", false);
        } else if (TUICalling.Type.VIDEO == mType) {
            mVideoFactory = new VideoLayoutFactory(this);
            mCallView = createVideoView(mRole, mType, mUserIds, mSponsorID, "", false);
        }
        mCallView.setOnAnswerCallback(this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mCallView.setLayoutParams(params);
        binding.parent.addView(mCallView);
        mCallView.enableFloatWindow(false);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestUser();
        if (!viewModel.isGirl()){
            viewModel.requestIsBlack();
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onCallAnswerEvent.observe(this, o -> startFee());
        viewModel.uc.onFeeErrorEvent.observe(this, o -> hangup());
        viewModel.uc.onDiamondRechargeEvent.observe(this, o -> YDialogUtil.getInstance().showNoDiamond(this, NoDiamondEnum.call, true));
        viewModel.uc.onPriceEvent.observe(this, o -> onPriceUI());
    }

    /**
     * 开始扣费
     */
    private Runnable mTimeRunnable;
    private int mTimeCount = 0;
    private int interval = 60;//每隔60秒扣一次费用
    private Handler mTimeHandler;

    private void startFee() {
        if (viewModel.isGirl() || viewModel.isFree()){
            return;
        }
        if (mTimeRunnable != null) {
            return;
        }
        if (mTimeRunnable == null) {
            mTimeRunnable = new Runnable() {
                @Override
                public void run() {
                    if (mTimeCount % interval == 0){
                        viewModel.requestVideoAudioFee();
                    }
                    mTimeCount++;
                    mTimeHandler.postDelayed(mTimeRunnable, 1000);
                }
            };
        }
        if (mTimeHandler == null){
            mTimeHandler = new Handler();
        }
        mTimeHandler.postDelayed(mTimeRunnable, 1000);
    }

    /**
     * 挂断
     */
    private void hangup() {
        if (mCallView != null){
            mCallView.hangup();
        }
    }

    @Override
    public void before(BooleanCallback callback) {
        if (viewModel.isGirl() || viewModel.isFree()){
            callback.onBoolean(true);
            return;
        }
        viewModel.requestVideoAudioIsEnough(mType, callback);
    }

    /**
     * 显示女方的通话价格
     * 条件：1.男的，2.接听时
     */
    private void onPriceUI() {
        if (!viewModel.isGirl() && TUICalling.Role.CALLED == mRole){
            String price = viewModel.otherUserEntity.getVideoPrice();
            if (TUICalling.Type.AUDIO == mType){
                price = viewModel.otherUserEntity.getVoicePrice();
            }
            mCallView.setVoicePrice(YStringUtil.removeZero(price));
        }
    }
}
